import Common from "../../utils/Common";
import { MSG } from "../../const/MSG";
import dataUtil from "./dataUtil";
import { AppConst } from "../../const/Const";
import { platformConf } from "../../platform/platformConf";
import { memoryConfig } from "./memoryConfig";
import { Debug } from "../../utils/Debug";


let ErrorType = {
    ONERROR: "HTTP协议链接出错",
    ONTIMEOUT: "HTTP协议链接超时",
    POSTERROR: "HTTP协议请求出错",
    RETURNERROR: "服务器返回错误code"
};
let GAME_COMMAND = {
    VERIFY_USER: 1,
    CREATE_ROLE: 2,
    CAPTAIN: 3
}


export class httpUtil {

    private appid: string = "";
    private secret: string = "";
    private versionNumber: string = "";
    public version: string = "2.1.0";
    private static instanceTime: number = Date.now();
    constructor() {
        // this.instanceTime = Date.now();
        // let versionUrl = `${ROOT_CONFIG.HTTP_ROOT}/SDK/version.json?t=` + Date.now();
        // if (Common.platform == AppConst.PC) {
        //     this.request(versionUrl, {}, 'GET', (res) => {
        //         if (this.version < res.version) {
        //             Debug.warn(`您的SDK版本号[${this.version}]不是最新版本，请尽快升级，最新版本[${res.version}]  下载地址：${res.download}`)
        //             if (!Common.isEmpty(res.memo))
        //                 Debug.warn(`${res.memo}`)
        //         }

        //     })
        // }
        // else if (Common.platform == AppConst.WX && window["wx"]) {
        //     this.request(versionUrl, {}, 'GET', (res) => {
        //         let aldVersion = window["wx"]["aldVersion"]
        //         if (!aldVersion || (aldVersion && aldVersion < res.aldVersion))
        //             Debug.warn(`阿拉丁文件错误，请重新下载${res.aldUrl}`)
        //     })
        // }



        // this.getShareInfo((data) => {
        //     platformUtil.currentPlatform.initShare(data);
        // });

        // this.loadCfg((res) => {
        //     Debug.log('remote config ', res)
        // })

    }


    /**
     * 请求服务
     * @param {*} url 
     * @param {*} data 
     * @param {*} method 
     * @param {*} success 
     * @param {*} fail 
     * @param {*} complete 
     */
    public static request(url: string, data: any, method: 'POST' | 'GET', success?: Function, fail?: Function, complete?: Function) {
        let newUrl = "";
        newUrl = url;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var response = xhr.responseText;
                if (xhr.status >= 200 && xhr.status < 400) {
                    var result = {};
                    try {
                        result = JSON.parse(response)
                    }
                    catch (e) {
                        Debug.error('json parse error ', response)
                        // if (fail)
                        //     fail(e);
                        result = response
                    }
                    // }
                    if (success)
                        success(result);
                }
                else {
                    Debug.warn('error ', response)
                    if (fail)
                        fail(response);
                }
            }
            else {
                // cc.log('caller state change  ', xhr)
                // Debug.log('caller state change  ', xhr)
            }
        };
        xhr.timeout = 10000;
        xhr.ontimeout = function (event) {
            Debug.error('error ', event)
            if (fail)
                fail(event);
        }

        if (method == "POST") {
            xhr.open('POST', newUrl);
            xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
            xhr.send(this._object2Query(data));
        }
        else {
            xhr.open(method, newUrl, true);
            xhr.send();
        }
    }
    public static _object2Query(obj: any) {
        var args = []
        for (var k in obj)
            args.push(k + "=" + obj[k])
        return args.join("&"); // 返回对象  
    }

    /**
     * Loading加载完成
     */
    public static finishLoading() {
        var g = window as any;
        if (g["kwaigame"])
            g["kwaigame"].readyGo();
        this.point("加载完成", {
            time: Date.now() - this.instanceTime
        });
    }
    /**
      * 点击了banner
      */
    public static clickBanner() {
        // this.point("点击了banner", {
        // });
    }

    /**
     * 看完了视频
     */
    public static clickVideo() {
        // this.point("点击视频", {
        // });
    }


    /**
     * 数据打点
     * @param name  打点名称
     */
    public static point(name: string, data: any = null) {
        var g = window as any;
        this.getAllConfig((res: any) => {
            if ((res && res.aldMonitorOn == 1)) {
                // if (platformUtil.currentApp == AppConst.WX) {
                //     if (g['wx'] && g['wx'].aldSendEvent)
                //         (g['wx'] as any).aldSendEvent(name, data);
                // }
                // else if (platformUtil.currentApp == AppConst.BYTEDANCE) {
                //     if (g['tt'] && g["tt"].reportAnalytics)
                //         g["tt"].reportAnalytics(name, data);
                // }
            }
        })
    }

    /**
    * 统计开始游戏
    * @param {string} level 关卡数 必须是1 || 2 || 1.1 || 12.2 格式
    */
    public static startGame(level: string) {
        var g = window as any;
        let e = {
            stageId: "" + level, //关卡ID， 必须是1 || 2 || 1.1 || 12.2 格式  该字段必传
            stageName: "" + level,//关卡名称，该字段必传
            userId: dataUtil.getToken() //用户ID
        }
        // if (platformUtil.currentApp == AppConst.WX) {
        //     if (g['wx'] && g['wx'].aldStage)
        //         g['wx'].aldStage.onStart(e);
        //     else
        //         Debug.warn(MSG.ALD_FILE_NO_IMPORT)
        // }
        // else if (platformUtil.currentApp == AppConst.BYTEDANCE) {
        //     this.point("startgame", e)
        // }
        // else
        //     Debug.log("startGame -> e", e)
    }
    /**
     * 统计结束游戏
     * @param {string} level 关卡数 必须是1 || 2 || 1.1 || 12.2 格式
     * @param {boolean} isWin 是否成功
     */
    public static endGame(level: string, isWin: boolean) {
        var g = window as any;
        var event = isWin ? "complete" : "fail";
        var desc = isWin ? "关卡完成" : "关卡失败";
        let e = {
            stageId: "" + level, //关卡ID， 必须是1 || 2 || 1.1 || 12.2 格式  该字段必传
            stageName: "" + level,//关卡名称，该字段必传
            userId: dataUtil.getToken(), //用户ID
            event: event,   //关卡完成  关卡进行中，用户触发的操作    该字段必传
            params: {
                desc: desc   //描述
            }
        }
        // if (platformUtil.currentApp == AppConst.WX) {
        //     if (g['wx'] && g['wx'].aldStage)
        //         g['wx'].aldStage.onEnd(e);
        //     else
        //         Debug.warn(MSG.ALD_FILE_NO_IMPORT)
        // }
        // else if (platformUtil.currentApp == AppConst.BYTEDANCE) {
        //     this.point(isWin ? 'gameEnd' : 'gameFail', {
        //         stageId: "" + level, //关卡ID， 必须是1 || 2 || 1.1 || 12.2 格式  该字段必传
        //         stageName: "" + level,//关卡名称，该字段必传
        //         userId: dataUtil.getToken(), //用户ID
        //     })
        // }
        // else
        //     Debug.log("startGame -> e", e)

    }
    /**
     * 视频统计
     * @param {number} type 0：视频点击 1：视频观看完成
     * @param {string} info 信息 ex:“领取三倍金币”
     * @param {string} level 关卡数
     */
    public static videoPoint(type: number, info: string, level: string) {
        var g = window as any;
        var name = type == 0 ? "点击视频" : "观看完成视频";
        let e = { info, level: level + "" }
        // if (platformUtil.currentApp == AppConst.WX) {
        //     this.point(name, e)
        // }
        // else if (platformUtil.currentApp == AppConst.BYTEDANCE) {
        //     this.point(type == 0 ? 'clickVideo' : 'endVideo', e)
        // }
        // else
        //     Debug.log("startGame -> e", e)

    }


    /**
     * 
     * @param callback 
     */
    public static getAllConfig(callback: Function) {
        this.loadCfg((res: any) => {
            callback({
                ...res
            })
        })
    }


    public static cfgData = {};
    public static areaData = null;
    public static _cfgQuene: Array<Function> = [];

    public static updateCache(key: string, value: any) {
        (this.cfgData as any)[key] = value;
    }


    public static loadCfg(callback: (data: any) => void) {
        if (!Common.isEmpty(this.cfgData)) {
            callback(this.cfgData);
        }
        else {
            this._cfgQuene.push(callback);
            if (this._cfgQuene.length > 1)
                return

            var url = "";
            if (Common.isEmpty(platformConf.config.url)) {
                this._cfgQuene.forEach(item => {
                    item(this.cfgData);
                });
                return;
            }
            else
                url = platformConf.config.url + "?t=" + Date.now();

            this.request(url, {}, 'GET',
                (res: any) => {
                    this._cfgQuene.forEach(item => {
                        item({ ...this.cfgData, ...res });
                    })
                    this._cfgQuene = [];
                },
                () => {
                    this._cfgQuene.forEach(item => {
                        item(this.cfgData);
                    })
                    this._cfgQuene = [];
                    Debug.log('load config json fail');
                }
            );
        }

    }

    public static setKey(keyName: string, keyValue: any) {
        (this.cfgData as any)[keyName] = keyValue;
    }

    public static addConfig(config: any) {
        for (let k in config) {
            (this.cfgData as any)[k] = config[k]
        }
    }




    /**
     * 原生广告状态
     * @param adunit 
     * @param type "display" || "click"
     * @param callback 
     */
    public static nativeAdStatus(adunit: string, type: string = "display" || "click", callback: (res: any) => void) {
        this.request('https://platform.qwpo2018.com/api/ad_cache/index', {
            "adunit": adunit,
            "type": type
        }, 'POST', (res: any) => {
            Debug.log('nativeAdStatus res ', res)
            if (callback)
                callback(res)
        })
    }

    public static levelStart(level: string) {
        let app;
        if (window['tt'] && window['tt'].uma) {
            app = window['tt'].uma;
        } else if (window['wx'] && window['wx'].uma) {
            app = window['wx'].uma;
        }
        if (app) {
            if (app.stage)
                app.stage.onStart({
                    stageId: level,
                    stageName: level
                })
            else
                Debug.log('app', app, 'app.stage', app.stage)
        }
    }

    public static levelEnd(level: string, isWin: boolean) {
        let app;
        if (window['tt'] && window['tt'].uma) {
            app = window['tt'].uma;
        } else if (window['wx'] && window['wx'].uma) {
            app = window['wx'].uma;
        }
        if (app) {
            let event = isWin ? "complete" : "fail";
            app.stage.onEnd({
                stageId: level,
                stageName: level,
                event: event
            })
        }
    }

    public static trackEvent(eventId: string, eventValue: string, extraValues: string[] = null) {
        // let data = { 'value': eventValue };
        // if (extraValues && extraValues.length > 0) {
        //     for (let i = 0; i < extraValues.length; i++) {
        //         data[`extraValue${(i + 1)}`] = extraValues[i];
        //     }
        // }
        // Debug.log("🚀 ~ file: httpUtil.ts ~ line 389 ~ trackEvent ~ data", data)
        
        let app;
        if (window['tt'] && window['tt'].uma) {
            app = window['tt'].uma;
        } else if (window['wx'] && window['wx'].uma) {
            app = window['wx'].uma;
        }
        if (app) {
            let data = { 'value': eventValue };
            if (extraValues && extraValues.length > 0) {
                for (let i = 0; i < extraValues.length; i++) {
                    data[`extraValue${(i + 1)}`] = extraValues[i];
                }
            }
            app.trackEvent(eventId, data);
        }
    }

    public static reportVideoStart(name: string, ...extraValues: string[]) {
        this.trackEvent('video_click', name, extraValues);
    }
    public static reportVideoFinish(name: string, ...extraValues: string[]) {
        this.trackEvent('video_finish', name, extraValues);
    }
}

